package de.lulusoft.anothertorrent.gui.commands;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.commands.IHandlerListener;

import de.lulusoft.anothertorrent.core.AnotherTorrentCore;
import de.lulusoft.anothertorrent.core.servers.Server;
import de.lulusoft.anothertorrent.gui.exceptions.ExceptionHandler;
import de.lulusoft.anothertorrent.gui.views.ConsoleView;

public class SendConsoleToServerCommand implements IHandler {
	
	public static final String ID = "de.lulusoft.anothertorrent.gui.commands.SendConsoleToServerCommand";
	public static final String P_COMMAND = "commandParameter";
	public static final String P_SERVER = "serverParameter";
	
//	private Server server = null;
	
//	public SendConsoleToServerCommand(Server server)
//	{
//		this.server = server;
//	}
	
	public SendConsoleToServerCommand()
	{
	}

	@Override
	public void addHandlerListener(IHandlerListener handlerListener) {
	}

	@Override
	public void dispose() {
	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		if (event.getTrigger() instanceof ConsoleView)
		{
			String rawCmds[] = event.getParameter(P_COMMAND).split(",");
			String serverName = event.getParameter(P_SERVER);
			
			Server server = AnotherTorrentCore.getDefault().getServerManager().getServerByName(serverName);
			String cmd = rawCmds[0].trim();
			String params[] = new String[rawCmds.length - 1];
			for (int i = 1; i < rawCmds.length; i++)
			{
				params[i-1] = rawCmds[i].trim();
			}
			Object result = null;
			try {
				result = server.getRTorrentManager().getXmlrpcManager().sendCommand(cmd, params);
			} catch (Exception e) {
				ExceptionHandler.alert("Error executing command", e);
			}
			String retval = "";
			retval = walkArray(result, 0);
			((ConsoleView)event.getTrigger()).appendServerText(retval);
			
		}
		return null;
	}
	
	private String walkArray(Object obj, int level)
	{
		String retval = "";
		String tabs = "";
		for (int i= 0; i < level; i++)
			tabs += "\t";
		if (obj instanceof Object[])
		{
			
			retval = tabs + "[\n";
			for (Object o : (Object[])obj)
			{
				retval += walkArray(o, level+1);
			}
			retval += tabs + "]\n";
		}
		else if (obj != null)
			retval = tabs + "\t" + obj.toString() + "\n";
		else
			retval = tabs + "\t" + "" + "\n";
		
		return retval;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

	@Override
	public boolean isHandled() {
		return true;
	}

	@Override
	public void removeHandlerListener(IHandlerListener handlerListener) {
	}

}
